package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.vo.WmNewsHandleVo;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @package com.heima.wemedia.service.impl
 * @Date 2022/3/3
 * @project heima-leadnews
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Value("${file.oss.web-site}")
    String website;
    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer id) {
        //校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //检查状态
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章状态异常");
        }
        //获取文章的文本内容和图片
        WmNewsHandleVo newsHandleVo = handleTextAndImages(wmNews);
        //敏感词审核
        boolean isSensitive = handleSensitive(newsHandleVo.getContent(), wmNews);
        if (!isSensitive) {
            return;
        }
        //阿里云文本审核
        Boolean isTextScan = handleTextScan(newsHandleVo.getContent(), wmNews);
        if (!isTextScan) {
            return;
        }
        //图片审核
        boolean isImagesScan = handleImagesScan(newsHandleVo.getImages(), wmNews);
        if (!isImagesScan) {
            return;
        }
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "自动审核通过");
        long time = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();
        long remainTime = time - nowTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE, PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId(), (message) -> {
                    message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return message;
                });
        log.info("文章发布通知成功文章id：{}",wmNews.getId());
    }

    /**
     * 阿里云图片审核
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            //判断是否违规
            switch (suggestion) {
                case "pass":
                    flag = true;
                    break;
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片涉嫌违规");
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "有违规嫌疑，转人工审核");
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核异常");
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云图片审核异常，转人工审核");

        }
        return flag;
    }

    /**
     * 阿里云文本审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;

        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    flag = true;
                    break;
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中有违规内容");
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中有不确定的内容，转人工审核");
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文章审核异常");
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云文章审核异常，转人工审核");
        }
        return flag;

    }

    /**
     * 敏感词审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        Boolean flag = true;
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (sensitives.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }

        List<String> allSensitives = sensitives.getData();
        SensitiveWordUtil.initMap(allSensitives);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap != null && resultMap.size() > 0) {
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "内容审核包含敏感词" + resultMap);
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    /**
     * 获取文章图片和文本列表
     *
     * @param wmNews
     * @return
     */
    private WmNewsHandleVo handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        WmNewsHandleVo newsHandleVo = new WmNewsHandleVo();

        //抽取文章文本
        List<Map> contentList = JSON.parseArray(content, Map.class);
        String contentStr = contentList.stream().filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.joining("_hmtt_"));
        contentStr += contentStr + "_hmtt_" + wmNews.getTitle();
        newsHandleVo.setContent(contentStr);
        //抽取文章图片
        List<String> images = contentList.stream().filter(map -> "image".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            List<String> collect = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> website + url)
                    .collect(Collectors.toList());
            images.addAll(collect);
        }
        images = images.stream().distinct().collect(Collectors.toList());
        //
        newsHandleVo.setImages(images);
        return newsHandleVo;

    }
}
